package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {
    @Autowired
    private IScheduleClient scheduleClient;

    @Autowired
    private WmNewsAutoScanService autoScanService;
    @Override
    public void addWmNewsToTask(WmNews wmNews) {
        Task task = new Task();
        task.setExecuteTime(wmNews.getPublishTime().getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());

        WmNews news = new WmNews();
        news.setId(wmNews.getId());
        task.setParameters(ProtostuffUtil.serialize(news));
        scheduleClient.addTask(task);

    }

    /**
     * 消费延迟队列
     */
    @Scheduled(fixedDelay = 10000)
    @Override
    public void scanNewsByTask() throws Exception {
        //1.通过Feign接口拉取任务
        ResponseResult responseResult = scheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());

        //2.判断是否拉取到了任务
        if (null != responseResult && responseResult.getCode() == 200 && null != responseResult.getData()){
            //3.如果拉取到了任务，就把任务中的参数取出来，获取到参数中的文字id 进行文字的审核操作
            String json = JSON.toJSONString(responseResult.getData());
            Task task = JSON.parseObject(json, Task.class);

            byte[] taskParameters = task.getParameters();
            WmNews wmNews = ProtostuffUtil.deserialize(taskParameters, WmNews.class);
            autoScanService.autoScanWmNews(wmNews.getId());
        }
            log.info("文章审核---消费任务执行---end---");
    }
}
